package com.beiming.libra.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;


/**
 * @Author: chenjt
 * @Description:
 * @Date: Created 2018-05-07 10:49
 */
@Slf4j
public class WordtoHtml {

  public static boolean docxToHtml(String filePath, String imagePath, String htmlPath) {
    try {
      File f = new File(filePath);
      if (!f.exists()) {
        log.info("sorry file does not exists");
        return false;
      } else {
        if (f.getName().endsWith(".docx") || f.getName().endsWith(".DOCX") || f.getName()
            .endsWith(".doc")) {
          //1:加载文档到XWPFDocument
          InputStream in = new FileInputStream(f);
          XWPFDocument document = new XWPFDocument(in);
          //2：加载图片到指定文件夹  07以上的 图片 image/word/media/
          File imgFile = new File(imagePath);
          XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imgFile));
          options.setExtractor(new FileImageExtractor(imgFile));
          //3：转换XWPFDocument to XHTML
          OutputStream out = new FileOutputStream(new File(htmlPath));
          XHTMLConverter.getInstance().convert(document, out, options);
        } else {
          log.info("Enter only MS Office 2007+ files");
        }
      }
    } catch (Exception e) {
      log.error("docxToHtml 转换失败!");
      return false;
    }
    return true;
  }


  // doc转换为html 此处暂时不用
  public static boolean docToHtml(String filePath, String imagePath, String htmlPath) {
    try {
      File imageDir = new File(imagePath);
      if (!imageDir.exists()) {
        imageDir.mkdirs();
      }
      HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(filePath));
      Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
      WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(document);
      // 保存图片，并返回图片的相对路径
      wordToHtmlConverter.setPicturesManager((content, pictureType, name, width, height) -> {
        //暂时注释
//        try {
//          FileOutputStream out = new FileOutputStream(imagePath + name);
//          out.write(content);
//        } catch (Exception e) {
//          e.printStackTrace();
//        }
        return "image/" + name;
      });
      wordToHtmlConverter.processDocument(wordDocument);
      Document htmlDocument = wordToHtmlConverter.getDocument();
      DOMSource domSource = new DOMSource(htmlDocument);
      StreamResult streamResult = new StreamResult(new File(htmlPath));

      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer serializer = tf.newTransformer();
      serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
      serializer.setOutputProperty(OutputKeys.INDENT, "yes");
      serializer.setOutputProperty(OutputKeys.METHOD, "html");
      serializer.transform(domSource, streamResult);
    } catch (Exception e) {
      log.error("doc 转换失败!");
      return false;
    }
    return true;
  }

  public static void main(String args[]) {
    try {

      //3个需要完整路径
      String filePath = "D:/test/CSS兼容性规范03.doc";
      String htmlPath = "D:/data/CSS兼容性规范03.html";
      String imagePath = "D:/data/image/";

      docxToHtml(filePath, imagePath, htmlPath);
      //docToHtml(filePath, imagePath, htmlPath);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }


}
